/*
 * Copyright (c) 2022 PATEO CONNECT+ (Nanjing) Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef CAR_VOICE_ASSISTANT_TTS_MANAGER_H
#define CAR_VOICE_ASSISTANT_TTS_MANAGER_H

#include "i_voice_cloud_manager.h"
#include "media_data_source.h"
#include "refbase.h"
#include <iostream>
#include <memory>
#include <mutex>
#include <player.h>
#include <string>

namespace OHOS {
namespace CarVoiceAssistant {

    class MediaDataSource : public OHOS::Media::IMediaDataSource {
    public:
        MediaDataSource(void* data, size_t size);
        ~MediaDataSource();

        int32_t ReadAt(int64_t pos, uint32_t length, const std::shared_ptr<OHOS::Media::AVSharedMemory>& mem) override;
        int32_t ReadAt(uint32_t length, const std::shared_ptr<OHOS::Media::AVSharedMemory>& mem) override;
        int32_t GetSize(int64_t& size) override;

    private:
        void* data_;
        int64_t size_;
    };

    class ITTSManagerCallback : public virtual RefBase {
    public:
        virtual void AudioPlayerStatusChanged(bool isPlaying) = 0;
    };

    class TTSManager : public RefBase {
    public:
        TTSManager();
        ~TTSManager();
        void RequestPlay(std::string text);
        void CancelAll();
        void ChangeSpeakerType(std::string speakerType);
        bool GetAudioPlayerIsPlaying();

        void OnPlayStateChanged(bool isPlaying);

        void SetCallback(wptr<ITTSManagerCallback> callback);

        IVoiceCloudManager* voiceCloudManager_;

    private:
        std::string currentText_;
        std::mutex mutex_;
        std::string speakerType_;

        std::shared_ptr<OHOS::Media::Player> player_;
        std::shared_ptr<MediaDataSource> source_;
        std::recursive_mutex player_recursive_mutex_;

        wptr<ITTSManagerCallback> callback_;
        bool isAudioPlaying_;

        void RunRequest(std::string text);

        void PlayTTS(void* data, size_t length);
        void CancelPlayTTS();
    };
}
}

#endif